/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.rbac.service.remove.impl;

import com.je.common.base.DynaBean;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 在上面
 */

@Service("rmoveAboveService")
public class MoveAboveServiceImpl extends AbstractMoveService {


    @Override
    @Transactional(rollbackFor = {RuntimeException.class})
    public void move(String tableCode, String id, String toId, DynaBean resourceBean, DynaBean targetBean) {
        updateDynaBeanTableInfo(resourceBean);
        updateDynaBeanTableInfo(targetBean);
        //平级移动
        if (sameLevel(resourceBean, targetBean)) {
            levelExchange(resourceBean, targetBean);
        } else {
            //不平级移动
            crossLevelExchange(resourceBean, targetBean);
        }
    }

    /**
     * 跨级资源替换fromBean资源以及下面的子资源
     */
    public void crossLevelExchange(DynaBean resourceBean, DynaBean targetBean) {
        DynaBean oldResourceOne = resourceBean.clone();

        resourceBean.setStr("SY_TREEORDERINDEX", targetBean.getStr("SY_TREEORDERINDEX"));
        resourceBean.setStr("SY_ORDERINDEX", targetBean.getStr("SY_ORDERINDEX"));
        String syParent = targetBean.getStr("SY_PARENT");

        if(resourceBean.getStr("TYPE").equals("department") && (targetBean.getStr("TYPE").equals("company") || targetBean.getStr("PARENT_NODETYPE").equals("company"))){
            syParent = "ROOT";
        }
        resourceBean.setStr("SY_PARENT", syParent);
        resourceBean.setStr("DEPARTMENT_PARENT",targetBean.getStr("SY_PARENT"));
        resourceBean.setStr("SY_PARENTPATH", targetBean.getStr("SY_PARENTPATH"));
        resourceBean.setStr("SY_PATH", String.format("%s/%s", targetBean.getStr("SY_PARENTPATH"), resourceBean.getPkValue()));
        //查询当前bean下是否有子级
        resourceBean.setStr("SY_NODETYPE",(findNextChildren(resourceBean)!=null && findNextChildren(resourceBean).size()>0)? "GENERAL" : "LEAF");
        resourceBean.setStr("SY_LAYER",targetBean.getStr("SY_LAYER"));

        buildCompanyInfo(resourceBean,targetBean);

        //将资源1的子级信息递归修改 SY_TREEORDERINDEX = '%s',SY_PARENT='%s',SY_PARENTPATH='%s',SY_PATH='%s'
        List<DynaBean> list = metaService.select("JE_RBAC_VCOMPANYDEPT", ConditionsWrapper.builder().eq("SY_PARENT", targetBean.getStr("SY_PARENT"))
                .ge("SY_ORDERINDEX", targetBean.getStr("SY_ORDERINDEX")).ne("ID", resourceBean.getPkValue()));

        metaService.update(resourceBean);
        getUpdateChildTreeOrderIndexSql(resourceBean, oldResourceOne);
        //平级信息加一,并替换下级的SY_TREEORDERINDEX
        for (DynaBean dynaBean : list) {
            DynaBean oldChild = dynaBean.clone();
            updateDynaBeanTableInfo(oldChild);
            updateDynaBeanTableInfo(dynaBean);
            treeIndexAddOne(dynaBean);
            getUpdateChildTreeOrderIndexSql(dynaBean, oldChild);
        }
    }




    public void levelExchange(DynaBean resourceBean, DynaBean targetBean) {
        DynaBean oldResourceOne = resourceBean.clone();
        resourceBean.setStr("SY_TREEORDERINDEX", targetBean.getStr("SY_TREEORDERINDEX"));
        resourceBean.setStr("SY_ORDERINDEX", targetBean.getStr("SY_ORDERINDEX"));

        String syParent = targetBean.getStr("SY_PARENT");

        if(resourceBean.getStr("TYPE").equals("department") && (targetBean.getStr("TYPE").equals("company") || targetBean.getStr("PARENT_NODETYPE").equals("company"))){
            syParent = "ROOT";
        }
        resourceBean.setStr("SY_PARENT", syParent);
        //更改当前资源的下级treeorderindex信息
//        metaService.executeSql("UPDATE "+resourceBean.getTableCode()+"SET SY_TREEORDERINDEX = {0} AND SY_ORDERINDEX={1} WHERE  "+resourceBean.getPkCode()+"={2}",
//                resourceBean.getStr("SY_TREEORDERINDEX"),resourceBean.getStr("SY_ORDERINDEX"),resourceBean.getStr("ID"));
        metaService.update(resourceBean);
        getUpdateChildTreeOrderIndexSql(resourceBean, oldResourceOne);

        //平级信息加一,并替换下级的SY_TREEORDERINDEX
        //递归修改目标资源和目标资源下面的资源，treeorder信息+1，
        List<DynaBean> list = metaService.select("JE_RBAC_VCOMPANYDEPT", ConditionsWrapper.builder().eq("SY_PARENT", targetBean.getStr("SY_PARENT"))
                .ge("SY_ORDERINDEX", targetBean.getStr("SY_ORDERINDEX")).ne("ID", resourceBean.getStr("ID")));

        for (DynaBean dynaBean : list) {
            DynaBean oldDynaBean = dynaBean.clone();
            updateDynaBeanTableInfo(dynaBean);
            treeIndexAddOne(dynaBean);
            getUpdateChildTreeOrderIndexSql(dynaBean, oldDynaBean);
        }
    }

}
